package com.zyk.leetcode;

import com.zyk.util.ListUtil;

/**
 * @author zhangsan
 * @date 2021/4/7 16:16
 */
public class M0202 {

    // https://leetcode-cn.com/problems/kth-node-from-end-of-list-lcci/
    // 双指针
    public static int kthToLast(ListNode head, int k) {
        ListNode fast = head, slow = head;
        /*for (int i = 0; i < k; i++) {
            fast = fast.next;
        }*/
        while (k > 0) {
            fast = fast.next;
            k--;
        }
        while (fast != null) {
            fast = fast.next;
            slow = slow.next;
        }
        return slow.val;
    }


    // for test
    public static void main(String[] args) {
        ListNode head = ListUtil.generateList(new int[]{1, 2, 3, 4, 5});
        int k = 2;
        System.out.println(kthToLast(head, k));

    }


}
